# -*- coding: utf-8 -*-
# @Time        :2025/8/21 14:27
# @Author      :文刀水寿
# @File        : cookie_tool.py
"""
 @Description :
"""
"""
cookies保存和测试
"""
import json
import re
import time
import os
import datetime
import uuid

from loguru import logger
from lib.feishu.feishu_bitable import FeishuBiTable
from setting import APP_1, FEISHU_KPI_BITABLE_APP_TOKEN
from spiders.dy.dy_creator_info import fetch_dy_creator_info as get_dy_creator_info
from spiders.ks.ks_creator import fetch_ks_creator_info
from spiders.xhs.xhs_creator_user_info import get_user_info as get_xhs_creator_info
from DrissionPage import Chromium, ChromiumOptions


# port range 0-65535 最好控制在9300-9500

class CookiesTool:

    def __init__(self, enable_browser=True, port_: int = None):
        if enable_browser:
            self.co = ChromiumOptions()
            self.co.set_argument('--start-maximized')
            if not port_:
                self.co.auto_port()
            else:
                print('??')
                time.sleep(1111)
                self.co.set_local_port(port_)

            # 初始化浏览器
            self.browser = Chromium(addr_or_opts=self.co)

        # 初始化飞书多为表格
        self.account_table_id = 'tbltUS8tnXx6jJFi'
        self.feishu_bitable = FeishuBiTable(app_config=APP_1, app_token=FEISHU_KPI_BITABLE_APP_TOKEN)

    def save_ck_to_feishu(self, platform: str):
        try:
            url_map = {
                'xhs':
                    {'login_url': 'https://creator.xiaohongshu.com/login',
                     'listen_api': 'https://creator.xiaohongshu.com/api/galaxy/creator/home/personal_info',
                     'function': self.xhs_listen},
                'dy':
                    {'login_url': 'https://creator.douyin.com/',
                     'listen_api': 'https://creator.douyin.com/web/api/media/user/info/',
                     'function': self.dy_listen},
                'ks':
                    {'login_url': 'https://cp.kuaishou.com/profile',
                     'listen_api': 'https://cp.kuaishou.com/rest/cp/creator/pc/home/userInfo',
                     'function': self.ks_listen}
            }

            function_run = url_map[platform]['function']
            record = function_run(login_url=url_map[platform]['login_url'], listen_api=url_map[platform]['listen_api'])
            if not record:
                logger.warning('Not record')

            user_name = record[0].get('账号昵称')
            platform = record[0].get('账号平台')
            cookies = {ck.get('name'): ck.get('value') for ck in json.loads(record[0].get('登录凭据'))}

            account_items = self.feishu_bitable.get_batch_records(table_id=self.account_table_id,
                                                                  filter_data={"conjunction": "and", "conditions": [
                                                                      {"field_name": "账号昵称", "operator": "is",
                                                                       "value": [user_name]},
                                                                      {"field_name": "账号平台", "operator": "is",
                                                                       "value": [platform]},
                                                                  ]}).get('data').get('items')
            logger.info(f'account_items: {account_items}')
            if not account_items:
                self.feishu_bitable.add_batch_record(table_id=self.account_table_id, fields=record)
                self.check_ck(user_name, platform, cookies)
                logger.info(f'account: {user_name}, platform: {platform}, add info success')
                return

            # 存在账号昵称和平台一样的就去更新
            account_info = account_items[0]
            account_info_record_id = account_info.get('record_id')
            self.feishu_bitable.update_record(table_id=self.account_table_id,
                                              record_id=account_info_record_id,
                                              fields={'平台号': record[0].get('平台号'),
                                                      '登录凭据': record[0].get('登录凭据'),
                                                      '凭据获取日期': int(time.time() * 1000)})

            self.check_ck(user_name, platform, cookies)
            logger.info(f'account: {user_name}, platform: {platform}, update info success')

        except Exception as e:
            logger.exception(e)

    def get_ck_from_feishu(self, platform: str, user_name: str):
        try:
            res = self.feishu_bitable.get_batch_records(table_id='tbltUS8tnXx6jJFi',
                                                        page_size=1,
                                                        filter_data={
                                                            "conjunction": "and",
                                                            "conditions": [{"field_name": "账号昵称", "operator": "is",
                                                                            "value": [user_name]},
                                                                           {"field_name": "账号平台", "operator": "is",
                                                                            "value": [platform]}]})
            logger.info(f'account_info: {res}')
            data = res.get('data').get('items')[0].get('fields').get('登录凭据')
            if len(data) == 1:
                cookies_list = json.loads(res.get('data').get('items')[0].get('fields').get('登录凭据')[0].get('text'))
            else:
                cookies_list = json.loads(''.join([item['text'] for item in data if 'text' in item]))

            cookies = {ck.get('name'): ck.get('value') for ck in cookies_list}
            return cookies

        except Exception as e:
            logger.exception(e)

    def xhs_listen(self, login_url, listen_api):
        tab = self.browser.new_tab()
        tab.get(login_url)

        tab.listen.start(listen_api)
        logger.info(f'开始监听xhs...')
        res = tab.listen.wait()
        if res.response.body:
            response_data = res.response.body
            logger.info(f'监听成功，response: {response_data}')
            data = response_data.get('data')
            user_name = data.get('name')
            red_num = data.get('red_num')
            fans_count = data.get('fans_count')
            platform = '小红书'
            cookies = tab.cookies()
            record = [{'账号昵称': user_name, '账号平台': platform, '平台号': red_num,
                       '登录凭据': json.dumps(cookies)}]
            logger.info(f'record: {record}')
            self.browser.quit()
            return record
        else:
            logger.error('监听失败，请查看具体原因！')

    def dy_listen(self, login_url, listen_api):

        tab = self.browser.new_tab()
        tab.get(login_url)
        # tab.set.cookies.clear()
        tab.refresh()
        tab.listen.start(listen_api)
        logger.info(f'开始监听dy...')
        res = tab.listen.wait()
        if res.response.body:
            response_data = res.response.body
            logger.info(f'监听成功，response: {response_data}')
            user = response_data.get('user')
            follower_count = user.get('follower_count')
            nickname = user.get('nickname')
            unique_id = user.get('unique_id', None)
            if not unique_id:
                unique_id = user.get('short_id')
            platform = '抖音'
            cookies = tab.cookies()
            record = [{'账号昵称': nickname, '账号平台': platform, '平台号': unique_id,
                       '登录凭据': json.dumps(cookies)}]
            logger.info(f'record: {record}')
            return record
        else:
            logger.error('监听失败，请查看具体原因！')

    def ks_listen(self, login_url, listen_api):
        tab = self.browser.new_tab()
        tab.get(login_url)
        # tab.set.cookies.clear()
        tab.refresh()
        tab.listen.start(listen_api)
        logger.info(f'开始监听ks')
        res = tab.listen.wait()
        if res.response.body:
            response_data = res.response.body
            logger.info(f'监听成功，response: {response_data}')
            data = response_data.get('data')
            core_user_info = data.get('coreUserInfo')
            user_name = core_user_info.get('userName')
            user_id = core_user_info.get('userId')
            platform = '快手'
            cookies = tab.cookies()
            record = [{'账号昵称': user_name, '账号平台': platform, '平台号': str(user_id),
                       '登录凭据': json.dumps(cookies)}]
            logger.info(f'record: {record}')
            return record
        else:
            logger.error('监听失败，请查看具体原因！')

    def check_ck(self, user_name: str = None, platform: str = None, cookies: dict = None):
        try:
            if not cookies and user_name and platform:
                cookies = self.get_ck_from_feishu(platform, user_name)

            if platform == '抖音':
                user_info = get_dy_creator_info(cookies)
                logger.info(f'dy user_info: {user_info}')
            elif platform == '小红书':
                user_info = get_xhs_creator_info(cookies)
                logger.info(f'xhs user_info: {user_info}')
            elif platform == '快手':
                user_info = fetch_ks_creator_info(cookies)
                logger.info(f'ks user_info: {user_info}')

        except Exception as e:
            logger.exception(e)

    def update_(self):

        res = self.feishu_bitable.get_batch_records(table_id='tbltUS8tnXx6jJFi',
                                                    filter_data={
                                                        "conjunction": "and",
                                                        "conditions": [{"field_name": "平台号", "operator": "is",
                                                                        "value": ["mtqishou"]},
                                                                       {"field_name": "账号平台", "operator": "is",
                                                                        "value": ['抖音']}]})
        logger.info(f'account_info: {res}')
        items = res.get('data').get('items')
        # print(items)
        # time.sleep(1111)
        for item in items:
            login_info = item.get('fields').get('登录凭据')
            print(login_info)
            if len(login_info) == 1:
                cookies_list = json.loads(res.get('data').get('items')[0].get('fields').get('登录凭据')[0].get('text'))
            else:
                cookies_list = json.loads(''.join([item['text'] for item in login_info if 'text' in item]))
            print(cookies_list)
            # time.sleep(1111)
            tab = self.browser.new_tab()
            # tab.get('https://creator.xiaohongshu.com/login')
            # tab.get('https://cp.kuaishou.com/profile')
            tab.get('https://creator.douyin.com/')
            # tab.get('https://cp.kuaishou.com/profile')
            # cookies = {ck.get('name'): ck.get('value') for ck in cookies_list}
            # print(f'cookies: {cookies}')
            tab.set.cookies(cookies=cookies_list)
            time.sleep(2)
            tab.refresh()
            time.sleep(1111)


def save_ck(platform):
    # port_num = 9400
    port_num = None
    tool: CookiesTool = CookiesTool(port_=port_num)
    tool.save_ck_to_feishu(platform)


def test_ck(user_name, platform):
    tool = CookiesTool(enable_browser=False)
    tool.check_ck(user_name, platform)


if __name__ == '__main__':
    # 保存ck
    # save_ck(platform='dy')
    # save_ck(platform='ks')
    save_ck(platform='xhs')

    # 测试ck
    # test_ck(user_name='陈大发认真变美', platform='抖音')
    # test_ck(user_name='陈大发认真变美', platform='抖音')
    # test_ck(user_name='神抢手第一干饭人', platform='小红书')
    # test_ck(user_name='闲眼包鱼哥', platform='快手')

    # 3、单独获取ck
    # tool = CookiesTool(enable_browser=False)
    # logger.info(tool.get_ck_from_feishu(platform='小红书', user_name='必吃榜'))

    # 4、
    # tool: CookiesTool = CookiesTool()
    # tool.update_()
